//
//  MainHandler.m
//  autocompilerCMD
//
//  Created by Vescky on 13-5-17.
//  Copyright (c) 2013年 Vescky. All rights reserved.
//

#import "MainHandler.h"
#import "packagerForIOS.h"
#import "pakagerForAndroid.h"
#import "FileOperator.h"
#import "PathParser.h"
#import "DataInfo.h"
#import "AppsProjectInfoParser.h"
#import "HomePageDataListItem.h"

@implementation MainHandler

#pragma mark - 打包的主要逻辑
- (void)serialRunWithArgs:(NSMutableDictionary*)argsDict {
    
    if (![argsDict objectForKey:@"enname"] || [[argsDict objectForKey:@"enname"] length] < 1){
        printf("\n#########   Error:Project must have a name!!type 'autoMaker help' for more details.   #########\n");
        exit(0);
    }
    
    NSString *appName = [argsDict objectForKey:@"enname"];
    NSString *iosPath = [argsDict objectForKey:@"ios"] ? [argsDict objectForKey:@"ios"] : @"";
    NSString *androidPath = [argsDict objectForKey:@"android"] ? [argsDict objectForKey:@"android"] : @"";
    NSString *zipUrlArg = [argsDict objectForKey:@"zipurl"] ? [argsDict objectForKey:@"zipurl"] : @"";
    NSString *identity = [argsDict objectForKey:@"profile"] ? [argsDict objectForKey:@"profile"] : @"";
    
    PathParser *pp = [PathParser sharePathParser];
    
    NSString *defPath = [argsDict objectForKey:@"mytemplate"] ? [argsDict objectForKey:@"mytemplate"] : @"";
    if (defPath && defPath.length > 1) {
        iosPath = [defPath stringByAppendingPathComponent:[NSString stringWithFormat:@"ios/%@",pp.templateProjectName]];
        androidPath = [defPath stringByAppendingPathComponent:[NSString stringWithFormat:@"android/%@",pp.templateProjectName]];
    }
    
    //设置workingSpace
    NSString *outPath = [argsDict objectForKey:@"out"];
    if (outPath && outPath.length > 1) {
        [self createWorkingSpace:outPath zipUrl:zipUrlArg];
    }
    
    [self redirectNSLogToDocumentFolder:pp.outputLogFilesPath]; //设置log日志储存目录
    NSLog(@">>>>>>>>>>>>>>>>>>>>>>>>>>>>> Let's get this party start! <<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
    
    //设置模板路径，若路径为default就不用更改路径
    if (iosPath.length > 0 && ![iosPath isEqualToString:@"default"]) {
        [pp setDefaultIosProjectPath:iosPath];
        [pp saveChanges:pp];
    }
    if (androidPath.length > 0 && ![androidPath isEqualToString:@"default"]) {
        [pp setDefaultAndroidProjectPath:androidPath];
        [pp saveChanges:pp];
    }
    
    //链接不为空，先下载zip包
    if (zipUrlArg.length > 0) {
        if ([zipUrlArg stringByMatching:@"http://"]) {
            NSLog(@">>>>>>>>>>>>>>>>>>>>>>>>>>>>>正在下载zip包...<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
            [[FileOperator shareFileOperator] synDownloadZipPackage:zipUrlArg];
        }
        else {
            NSLog(@">>>>>>>>>>>>>>>>>>>>>>>>>>>>>正在解压zip包...<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
            zipUrlArg = [zipUrlArg stringByReplacingOccurrencesOfString:@"file:" withString:@""];
            int waitingZipCounter = 0;
            //zip包可能有延时，最多等待180s
            while (waitingZipCounter < 36) {
                if ([[NSFileManager defaultManager] fileExistsAtPath:zipUrlArg]) {
                    break;
                }
                else {
                    NSLog(@">>>>>> Zip file:\"%@\"not exist!Retry 5s later.counter:%d <<<<<<",zipUrlArg,waitingZipCounter);
                   [NSThread sleepForTimeInterval:5.0];
                    waitingZipCounter++;
                }
            }
            if ([[NSFileManager defaultManager] fileExistsAtPath:zipUrlArg]) {
               NSString *zPath = [pp.incomeBundlePath stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"/%@",pp.incomeBundleName] withString:@""];
                NSString *str = [NSString stringWithFormat:@"%@/ChangeZipToBundle.sh %@ %@",pp.scriptFilesPath,zipUrlArg,zPath];
                system([str UTF8String]);
            }
            else {
                NSLog(@"##########################  ERROR:zip file doesn't exist! %@ ##########################",zipUrlArg);
                exit(0);
            }
        }
    }
    
    //下载证书
    DataInfo *dInfo = [AppsProjectInfoParser parseDataInfo];
    if (dInfo.certificateDownLoadLink && [dInfo.certificateDownLoadLink stringByMatching:@"http://"]) {
        [[FileOperator shareFileOperator] synDownloadCertsPackage:dInfo.certificateDownLoadLink];
    }
    
    if (!dInfo.runPlatform && dInfo.runPlatform.length <= 0) {
        dInfo.runPlatform = @"MP1-CN";
    }
    
    pp = [PathParser initPathParserWithWithMode:[[argsDict objectForKey:@"mode"] intValue] runPlatform:dInfo.runPlatform ];//workFolder:outPath
    
    NSString *buildArg = [argsDict objectForKey:@"build"];
    NSString *environmentArg = [argsDict objectForKey:@"environment"] ? [argsDict objectForKey:@"environment"] : @"prod";
    NSString *saveLogs = [argsDict objectForKey:@"savelogs"];
    //    NSString *xmppEnvironment = @"";
    NSString *serverIp = @"";
    NSString *xmppIp = @"";
    NSString *appType = @"";
    
    if ([environmentArg isEqualToString:@"wip"]) {
        serverIp = pp.wipServerIP;
        xmppIp = pp.wipXmppIP;
        appType = @"preview";
    }
    else {
        serverIp = pp.prodServerIP;
        xmppIp = pp.prodXmppIP;
        appType = @"publish";
    }
    
#pragma mark - pre-production ip setting
    //判断是否为pre-production
    if ([environmentArg stringByMatching:@"test"]) {
        if ([environmentArg stringByMatching:@"wip"]) {
            serverIp = pp.testWipServerIP;
            xmppIp = pp.testWipXmppIP;
            appType = @"preview";
        }
        else {
            serverIp = pp.testProdServerIP;
            xmppIp = pp.testProdXmppIP;
            appType = @"publish";
        }
    }
#pragma mark - pre-production End
    
    bool flagSaveLogs = NO;
    if (saveLogs && saveLogs.length > 0) {
        flagSaveLogs = YES;
    }
    
    bool flagIos = NO,flagAndroid = NO;
    if (iosPath && iosPath.length > 0) {
        flagIos = YES;
    }
    if (androidPath && androidPath.length > 0) {
        flagAndroid = YES;
    }
    
    bool needBuild = NO;
    if (buildArg && [buildArg isEqualToString:@"YES"]) {
        needBuild = YES;
    }
    
    //优化zip包
    NSString *hpLayout = [self getHomepageLayoutNumber];
    NSString *optimizeCmd = [NSString stringWithFormat:@"%@/optimizeZip.sh %@ %@",pp.scriptFilesPath,pp.incomeBundlePath,hpLayout];
    system([optimizeCmd UTF8String]);
    
    //检查zip包完整性
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:[NSString stringWithFormat:@"%@/doc/project.info",pp.incomeBundlePath]] || ![fm fileExistsAtPath:[NSString stringWithFormat:@"%@/doc/data.info",pp.incomeBundlePath]]) {
        NSLog(@"\n##########################  ERROR:Zip包不完整! \n%@  \n%@ ########################## \n",pp.incomeBundlePath,zipUrlArg);
        exit(0);
    }
    
    packagerForIOS *pIOS = [packagerForIOS sharePackagerForIOS];
    pakagerForAndroid *pAndroid = [pakagerForAndroid sharePakagerFroAndroid];
    
    
    NSMutableDictionary *dictToBuild = [[NSMutableDictionary alloc] initWithObjectsAndKeys:appName,@"enname",serverIp,@"environment",identity,@"identity",xmppIp,@"xmppIp",appType,@"appType", nil];
    if (buildArg) {
        [dictToBuild setObject:buildArg forKey:@"build"];
    }
    if (saveLogs) {
        [dictToBuild setObject:saveLogs forKey:@"save"];
    }
    if ([argsDict objectForKey:@"mode"]) {
        [dictToBuild setObject:[argsDict objectForKey:@"mode"] forKey:@"mode"];
    }
    
    NSLog(@"[[[ dictToBuild:%@ ]]]",dictToBuild);
    if (flagIos) {
        [pIOS autoCompileIOSWithContent:dictToBuild];
    }
    if (flagAndroid) {
        [pAndroid autoCompileAndroidWithContent:dictToBuild];
    }
    
//    if (flagAndroid) {
//        [pAndroid autoCompileAndroid:appName environment:environmentArg createLogFile:flagSaveLogs];
//        if (buildArg) {
//            [pAndroid androidBuildWithLogFiles:flagSaveLogs];
//        }
//    }
    
}

#pragma mark - 创建一个临时目录，作为工作区
- (void)createWorkingSpace:(NSString *)path zipUrl:(NSString*)zipUrl {
    NSFileManager *fm = [NSFileManager defaultManager];

//    if ([fm fileExistsAtPath:path]) {
//        [fm removeItemAtPath:path error:nil];
//    }
    
    int i = 1;
    NSString *temPath = path;    
    while ([fm fileExistsAtPath:path]) {
        path = [temPath copy];
        path = [path stringByAppendingString:[NSString stringWithFormat:@"%d",i]];
        i++;
    }
    //创建这个目录
    [fm createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
    NSLog(@">>>>>>>>>>>>> workingSpace:%s <<<<<<<<<<<<<<\n",[path UTF8String]);
    
//    path = [path stringByAppendingPathComponent:@"autocompilerWorkingSpace"];
//    [fm createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
    
    //创建workingSpace中的内容
    [fm createDirectoryAtPath:[path stringByAppendingPathComponent:@"products"] withIntermediateDirectories:NO attributes:nil error:nil];
    [fm createDirectoryAtPath:[path stringByAppendingPathComponent:@"logs"] withIntermediateDirectories:NO attributes:nil error:nil];
    [fm createDirectoryAtPath:[path stringByAppendingPathComponent:@"out"] withIntermediateDirectories:NO attributes:nil error:nil];
    [fm createDirectoryAtPath:[path stringByAppendingPathComponent:@"out/android"] withIntermediateDirectories:NO attributes:nil error:nil];
    [fm createDirectoryAtPath:[path stringByAppendingPathComponent:@"out/ios"] withIntermediateDirectories:NO attributes:nil error:nil];
    [fm createDirectoryAtPath:[path stringByAppendingPathComponent:@"tmp"] withIntermediateDirectories:NO attributes:nil error:nil];
    
    PathParser *pp = [PathParser sharePathParser];
    [pp setOutputLogFilesPath:[path stringByAppendingPathComponent:@"logs"]];
    [pp setOutIosProjectPath:[path stringByAppendingFormat:@"/out/ios/%@",pp.templateProjectName]];
    [pp setOutAndroidProjectPath:[path stringByAppendingFormat:@"/out/android/%@",pp.templateProjectName]];
    [pp setOutputAppPath:[path stringByAppendingPathComponent:@"products"]];
    [pp saveChanges:pp];
    
    
    //遍历libs目录，复制Android的libs过去
    NSString *outLibsPatn = [path stringByAppendingPathComponent:@"out/android/libs"];
    [fm createDirectoryAtPath:outLibsPatn withIntermediateDirectories:NO attributes:nil error:nil];
    NSMutableArray *libsList = [[FileOperator shareFileOperator] getListOfPath:pp.defaultAndroidLibsPath isDir:YES];
    for (int i = 0; i < [libsList count]; i++) {
        NSString *libName = [libsList objectAtIndex:i];
        if (![libName isEqualToString:@"AppsTemplate"]) {
            //非模板的文件夹，是libs
            NSString *toPath = [outLibsPatn stringByAppendingPathComponent:libName];
            if (![fm fileExistsAtPath:toPath]) {
                //不存在，复制过去，存在就不用了
                [fm copyItemAtPath:[pp.defaultAndroidLibsPath stringByAppendingPathComponent:libName] toPath:toPath error:nil];
            }
        }
    }
    
    
    if (zipUrl.length > 0) {
        //有zip包，才会去用out中的zipPackage目录
        [pp setIncomeBundlePath:[path stringByAppendingFormat:@"/tmp/%@",pp.incomeBundleName]];
        [pp saveChanges:pp];
    }
}

- (NSString*)getHomepageLayoutNumber {
    DataInfo *dataInfo = [AppsProjectInfoParser parseDataInfo];
    HomePageDataListItem *hpItem = [dataInfo.dataList objectAtIndex:1];
    NSString *layoutNumber = [hpItem.layout stringByReplacingOccurrencesOfString:@"layout" withString:@""];
    return layoutNumber;
}

#pragma mark - 把log输出到一个文件
- (void)redirectNSLogToDocumentFolder:(NSString*)logDir {
    freopen([[logDir stringByAppendingPathComponent:@"autocompile.log"] cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
    freopen([[logDir stringByAppendingPathComponent:@"autocompile.log"] cStringUsingEncoding:NSASCIIStringEncoding],"a+",stdout);
}


@end
